<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请部门" prop="dept_id">
        <treeselect v-model="queryParams.dept_id" :options="deptOptions" :normalizer="normalizer" placeholder="请选择部门" style="width:180px" />
      </el-form-item>
      <el-form-item label="采购人" prop="user_id">
        <el-select v-model="queryParams.user_id" placeholder="请选择采购人" filterable clearable>
          <el-option
            v-for="u in userOptions"
            :key="u.value"
            :label="u.label"
            :value="u.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购编号" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入采购编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购进度" prop="apply_status">
        <el-select v-model="queryParams.apply_status" placeholder="请选择采购进度" clearable>
          <template v-for="dict in dict.type.flow_apply_status">
          <el-option v-if="dict.value != '1'"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="完成时间" prop="finish_time">
        <el-date-picker
          v-model="queryParams.finish_time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:purchase:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购编号" align="center" prop="num" />
      <el-table-column label="采购原由" align="center" prop="reason" />
      <el-table-column label="采购说明" align="center" prop="comment" />
      <el-table-column label="总价值" align="center" prop="price" />
      <el-table-column label="申请部门" align="center" prop="dept_name" />
      <el-table-column label="申请人" align="center" prop="user_name" />
      <el-table-column label="申请时间" align="center" prop="apply_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.apply_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="finish_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finish_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购状态" align="center" prop="apply_status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.flow_apply_status" :value="scope.row.apply_status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.apply_status == '2'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleStart(scope.row)"
          >开始</el-button>
          <el-button v-if="scope.row.apply_status == '3'"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleFinish(scope.row)"
          >完成</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
    <!-- 添加或修改采购申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" disabled>
        <el-form-item label="采购编号" prop="num" v-if="form.id">
          <el-input v-model="form.num" placeholder="自动生成" readonly/>
        </el-form-item>
        <el-form-item label="采购原由" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入采购原由" />
        </el-form-item>
        <el-form-item label="采购说明" prop="comment">
          <el-input v-model="form.comment" type="textarea" rows="3" placeholder="请输入采购说明" />
        </el-form-item>
        <el-row v-if="form.id">
          <el-col :span="12">
        <el-form-item label="申请部门" prop="dept_id">
          <el-input v-model="form.dept_name" placeholder="请输入申请部门" readonly/>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="申请人" prop="user_id">
          <el-input v-model="form.user_name" placeholder="请输入申请人" readonly/>
        </el-form-item>
          </el-col>
          </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="总价值" prop="price">
          <el-input v-model="form.price" placeholder="请输入总价值" readonly/>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="完成时间" prop="finish_time" v-if="form.status=='4'">
          <el-date-picker clearable
            v-model="form.finish_time"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
          </el-col>
          </el-row>
        <el-divider content-position="center">采购明细信息</el-divider>
        <el-table :data="assetPurchaseDetailList" :row-class-name="rowAssetPurchaseDetailIndex" ref="assetPurchaseDetail">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="型号" prop="model_id" width="150">
            <template slot-scope="scope">
              {{filterModelName(scope.row.model_id)}}
            </template>
          </el-table-column>
          <el-table-column label="购买数量" prop="amount" width="150" />
          <el-table-column label="入库资产" prop="nums" width="200" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiPatch, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Purchase",
  components: {
    Treeselect
  },
  dicts: ['flow_check_status', 'flow_apply_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 子表选中数据
      checkedAssetPurchaseDetail: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请表格数据
      purchaseList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 采购明细表格数据
      assetPurchaseDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      userOptions: [],
      deptOptions: [],
      // 查询参数
      queryParams: {
        num: null,
        reason: null,
        comment: null,
        price: null,
        check_status: '2',
        dept_id: null,
        user_id: null,
        finish_time: [],
        apply_time: null,
        apply_status: null,
        "@alias": "t",
        "@exp": {
          finish_time: 'bt'
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      modelOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reason: [
          { required: true, message: "采购原由不能为空", trigger: "blur" }
        ],
        dept_id: [
          { required: true, message: "申请部门不能为空", trigger: "blur" }
        ],
        user_id: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    apiDs('user_select').then(response=>{
        this.userOptions = response.data;
    });
    apiDs('dept_select').then(response=>{
        this.deptOptions = this.handleTree(response.data, "value", "parent_id");
    });
    let cateModel = {
      "asset_model":{
        "@column":"id,name,price",
        "@alias":"t"
      },
      "asset_category":{
        "@column":"id:cate_id,name:cate_name",
        "@alias":"c",
        "@join":"c.id = t.cate_id"
      },
      "@pager":{
        page:1,
        limit:1000
      }
    };
    apiGet(cateModel).then(response=>{
      let models = [];
      if(response.data.rows){
        response.data.rows.forEach(function(row){
          models.push({
            value:row.id,
            label: row.cate_name+' ' + row.name,
            price:row.price,
            cate_id:row.cate_id
          })
        })
      }
      this.modelOptions = models;
    });
  },
  methods: {
    /** 查询采购申请列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['asset_purchase'] = {...this.queryParams};
      if(this.queryParams['finish_time'].length == 0){
          params['asset_purchase']['finish_time'] = null;
      }      
      params['sys_user'] = {
          "@alias": "u",
          "@join": "LEFT u.user_id = t.user_id",
          "@column":"nick_name user_name"
      };
      params['sys_dept'] = {
          "@alias": "d",
          "@join": "LEFT d.dept_id = t.dept_id",
          "@column":"dept_name"
      };
      params['@pager'] = this.pager;
      apiGet(params).then(response => {
        this.purchaseList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        num: this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')+'1'+Math.ceil(Math.random()*10),
        reason: null,
        comment: null,
        price: null,
        check_status: null,
        dept_id: "@orgId()",
        user_id: "@userId()",
        apply_time: null,
        finish_time: null,
        apply_status: '1'
      };
      this.assetPurchaseDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
        let data = {
          'asset_purchase': { 
            "@column":"*",
            "@alias":"t",
            id:id
          },
          'sys_user': { 
            "@column":"nick_name:user_name",
            "@alias":"u",
            "@join":"u.user_id = t.user_id",
          },
          'sys_dept': { 
            "@column":"dept_name",
            "@alias":"d",
            "@join":"d.dept_id = t.dept_id",
          }
        };
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购申请";
      });
      apiGet({"@table":"asset_purchase_detail","@pager":{limit:1000}, "purchase_id":id}).then(response => {
        this.assetPurchaseDetailList = response.data.rows;
      });
    },
	/** 采购明细序号 */
    rowAssetPurchaseDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    filterModelName(modelId) {
      for(var j=0;j<this.modelOptions.length;j++){
          if(this.modelOptions[j].value == modelId){
            return this.modelOptions[j].label;
          }
        }
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['asset_purchase'] = {...this.queryParams};
      if(this.queryParams['finish_time'].length == 0){
          params['asset_purchase']['finish_time'] = null;
      }
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    },
    /** 开始按钮操作 */
    handleStart(row) {
      let data = {
        asset_purchase: {
            id: row.id,
            finish_time: "@now()",
            apply_status:"3"
        },
        "@ignore":true,
        "@tags": ['asset_purchase']
      };
      apiPut(data).then(response => {
          this.getList();
      });
    },
    /** 完成按钮操作 */
    handleFinish(row) {
      let data = {
        asset_purchase: {
            id: row.id,
            finish_time: "@now()",
            apply_status:"4"
        },
        "@ignore":true,
        "@tags": ['asset_purchase']
      };
      apiPut(data).then(response => {
          this.getList();
      });
    }
  }
};
</script>
